/*!
 * 
 *  jQuery GWSSI Optimus UI GuiGrid v1.0
 *  http://www.gwssi.com.cn
 *  
 * 	Copyright 2011,zh_di
 * 	
 * 	Re. flexigrid.js v1.1
 * 	http://flexigrid.info/
 *  Copyright 2011,Paulo P. Marinas 
 *  
 * 	Date: Wed May 4 15:11:21 2011
 */
(function($) {
	/*********************
	 * 
	 * 	 基础Class类
	 * 
	 */
	var Class = {
		create : function() {
			return function() {
				this.initialize.apply(this, arguments);
			};
		}
	};
	
	/*********************
	*
	*	Grid列表数据类 
	* 
	*/
	var GridBody = Class.create();
	GridBody.prototype = {
		/**
		 * 初始化
		 * @param data 数据区数据
		 * @param options 参数
		 * @param headclass GridHead类
		 */
		initialize : function(data,options,headclass){
			this.data = data;
			this.options = options;
			this.headclass = headclass;
		},
		option : function(options){
			this.data = options.data;
			this.options = options.options;
			this.headclass = options.headclass;
		},
		/**
		 * JSON格式生成HTML
		 * @param data 数据区数据
		 * @param p	   参数
		 * @param head GridHead类
		 * @returns {Array} 
		 */
		getJSONHtml : function(data,options,headclass,hDiv){
			var tbhtml = $("<table/>")
				.addClass("tbtable")
				.attr({"cellpadding":"0","cellspacing":"0","border":"0"});
			var headarray = headclass.getGridHeadData(hDiv);
			var tbbody = $("<tbody/>");
			if (data.rows != null) {
                $.each(data.rows, function(i, row) {
                	var trid = row[options.keyCol];
                	
                	var tbtr = $("<tr/>")
                		.attr("id","row"+trid);
                    if (i % 2 && options.striped) {//斑纹显示
                        tbtr.addClass("erow");
                    }
                    
                    for(var j =0; j< headarray.length; j++){//循环gridhead 根据参数设置数据区显示格式
                        var tddata = "";
                        var tdclass = "";
                        var headdata = headarray[j];
                        var tbtd = $("<td/>")
                        	.attr("align",headdata.align);
                        var idx = headdata.axis;
                        if (options.sortname && options.sortname == headdata.abbr) {//已排序显示
                            tbhtml.addClass("sorted");
                        }
                        if (headdata.hide) {//是否展示
                            tbtd.css("display","none")
                        }
                        var width = headdata.width;
                        var tbdiv = $("<div/>")
                        	.css({"text-align":headdata.align,"width":width});
                        if (options.nowrap == false) {
                            tbdiv.css("white-space","normal")
                        }
                        if (idx == "-1") { //checkbox 数值为-1
                        	var tbinput = $("<input/>")
                        		.attr({"type":"checkbox","id":"chk_"+trid})
                        		.addClass("itemchk")
                        		.val(trid);
                            tbhtml.addClass("chboxtd");
                            tbinput.appendTo(tbdiv);
                            tbinput = null;
                        }
                        else {
							var divInner;
							for(var rd in row){
                        		if(headclass.data[idx].name == rd){
                        			divInner = row[rd] || "&nbsp";
                        			break;
                        		}
                        	}
                            if (options.process) {
                                divInner = options.process(divInner, trid);
                            }
                            tbdiv.text(divInner);
                            divInner = null;
                        }
                        tbdiv.appendTo(tbtd);
                        tbdiv = null;
                        tbtd.appendTo(tbtr);
                        tbtd = null;
                    }
                    tbtr.appendTo(tbbody);
                    tbtr = null;
                });
            }
            tbhtml.append(tbbody);
            tbbody = null;
			return tbhtml;
		},
		/**
		 * 数据区HTML
		 * @returns
		 */
		getBodyHtml : function (hDiv){
			var options = this.options;
			var data = this.data;
			var headclass = this.headclass;
        	return this.getJSONHtml(data,options,headclass,hDiv);
		}
	};
	/*********************
	*
	*	Grid表头数据 
	* 
	*/
	var GridHead = Class.create();
	GridHead.prototype = {
		/**
		 * 初始化
		 * @param data 表头数据
		 * @param showcheckbox 是否显示checkbox参数
		 */
		initialize : function(data,showcheckbox){
			this.data = data;
			this.showcheckbox = showcheckbox;
		},
		reload : function(data,showcheckbox){
			this.data = data;
			this.showcheckbox = showcheckbox;
			return this.getHeadHtml();
		},
		/**
		 * 获取Grid表头HTML
		 * @returns
		 */
		getHeadHtml : function(){
			var d = this.data;
			var showcheckbox = this.showcheckbox;
			thead = document.createElement('thead');
            tr = document.createElement('tr');
            if (showcheckbox) {//checkbox
                var cth = jQuery('<th/>');
                var cthch = jQuery('<input type="checkbox"/>');
                cthch.addClass("noborder");
                cth.addClass("cth")
                	.attr({ "axis": "col-1", width: "22", "isch": true })
                	.append(cthch);
                $(tr).append(cth);
            }
            for (i = 0; i < d.length; i++) {
                var cm = d[i];
                var th = document.createElement('th');
                th.innerHTML = cm.display;
                if (cm.name && cm.sortable)
                    $(th).attr('abbr', cm.name);
                $(th).attr('axis', 'col' + i);
                if (cm.align)
                    th.align = cm.align;
                if (cm.width)
                    $(th).attr('width', cm.width);
                if (cm.hide) {
                    th.hide = true;
                }
                if (cm.toggle != undefined) {
                    th.toggle = cm.toggle;
                }
                if (cm.process) {
                    th.process = cm.process;
                }
                $(tr).append(th);
            }
            $(thead).append(tr);
			return thead;
		},
		/**
		 * 获取Grid表头数据列表，用于添加数据区数据使用
		 * @returns {Array}
		 */
		getGridHeadData : function(hDiv){
			var ths = $('tr:first th', hDiv);
            var thsdivs = $('tr:first th div', hDiv);
            var data = [];
            ths.each(function(i){
            	var d = {};
            	d.align = this.align;//文字位置
            	d.hide = this.hide;//是否隐藏
            	d.axis = $(this).attr('axis').substr(3);//col名称
            	d.abbr = $(this).attr('abbr');//是否排序
            	d.width = thsdivs[i].style.width;//宽度
            	d.process = this.process;//方法体
            	data.push(d);
            });
            return data;
		} 
	};
	/*********************
	*
	*	Grid总体框架 
	* 
	*/
	var GuiGrid = Class.create();
	GuiGrid.prototype = {
		/**
		 * 初始化
		 * @param $widget 
		 */
		initialize : function($widget){
			this.$widget = $widget;
			this.self = $widget.element;
			this.options = $.extend({},$.ui.guigrid.prototype.options,$widget.options);
			this.grid = {};
		},
		/**
		 * 初始化gDiv
		 */
		initgDiv : function(){
			var g = this.grid;
			var p = this.options;
			var t = this.self;
			//set gDiv
	        g.gDiv.className = p.gridClass;
	        if (p.width != 'auto') g.gDiv.style.width = p.width + 'px';
	        //add conditional classes
	        if ($.browser.msie)
	            $(g.gDiv).addClass('ie');
	        if (p.novstripe)
	            $(g.gDiv).addClass('novstripe');
	        $(t).before(g.gDiv);
	        $(g.gDiv)
			.append(t);
		},
		/**
		 * 初始化hDiv
		 */
		inithDiv : function (){
			var g = this.grid;
			var t = this.self;
			var p = this.options;
			if (p.colModel) {
	            g.head = new GridHead(p.colModel,p.showcheckbox);
	        }
			//set hDiv
	        g.hDiv.className = 'hDiv';
	        $(t).before(g.hDiv);
			g.hTable.cellPadding = 0;
	        g.hTable.cellSpacing = 0;
	        $(g.hDiv).append('<div class="hDivBox"></div>');
	        $('div', g.hDiv).append(g.hTable);
	        var thead = g.head.getHeadHtml();
	        if (thead) $(g.hTable).append(thead);
	        thead = null;
	        this.bindHeadEvent();
		},
		
		/**
		 * 初始化hDiv
		 */
		bindHeadEvent : function(){
			var g = this.grid;
			var t = this.self;
			var p = this.options;
			var f = this;
	        if (!p.colmodel) var ci = 0;
	        //setup thead			
	        $('thead tr:first th', g.hDiv).each(function() {//表头
		 	    var thdiv = document.createElement('div');
		 	    $(this).unbind();
		 	    if ($(this).attr('abbr')) {//可排序
		 	        $(this).click(//添加click方法
							function(e) {
							    if (!$(this).hasClass('thOver')) return false;
							    var obj = (e.target || e.srcElement);
							    if (obj.href || obj.type) return true;
							    f.changeSort(this);
							}
						);
		 	        if ($(this).attr('abbr') == p.sortname) {//已经排序
		 	            this.className = 'sorted';
		 	            thdiv.className = 's' + p.sortorder;
		 	        }
		 	    }
		 	    if (this.hide) $(this).hide();//是否隐藏
		 	    if (!p.colmodel && !$(this).attr("isch")) {//col序号
		 	        $(this).attr('axis', 'col' + ci++);
		 	    }
		 	    $(thdiv).css({ textAlign: this.align, width: this.width + 'px' });
		 	    thdiv.innerHTML = this.innerHTML;
		 	    $(this).empty().append(thdiv).removeAttr('width');
		 	    if (!$(this).attr("isch")) {//绑定事件
		 	        $(this).mousedown(function(e) {//mousedown
		 	            f.dragStart('colMove', e, this);
		 	        })
					.hover(function() {//hover
					    if (!g.colresize && !$(this).hasClass('thMove') && !g.colCopy) $(this).addClass('thOver');
					    if ($(this).attr('abbr') != p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) $('div', this).addClass('s' + p.sortorder);
					    else if ($(this).attr('abbr') == p.sortname && !g.colCopy && !g.colresize && $(this).attr('abbr')) {
					        var no = '';
					        if (p.sortorder == 'asc') no = 'desc';
					        else no = 'asc';
					        $('div', this).removeClass('s' + p.sortorder).addClass('s' + no);
					    }
					    if (g.colCopy) {
					        var n = $('th', g.hDiv).index(this);
					        if (n == g.dcoln) return false;
					        if (n < g.dcoln) $(this).append(g.cdropleft);
					        else $(this).append(g.cdropright);
					        g.dcolt = n;
					    } else if (!g.colresize) {
					        var thsa = $('th:visible', g.hDiv);
					        var nv = -1;
					        for (var i = 0, j = 0, l = thsa.length; i < l; i++) {
					            if ($(thsa[i]).css("display") != "none") {
					                if (thsa[i] == this) {
					                    nv = j;
					                    break;
					                }
					                j++;
					            }
					        }
					        var onl = parseInt($('div:eq(' + nv + ')', g.cDrag).css('left'));
					        var nw = parseInt($(g.nBtn).width()) + parseInt($(g.nBtn).css('borderLeftWidth'));
					        nl = onl - nw + Math.floor(p.cgwidth / 2);
					        $(g.nDiv).hide(); $(g.nBtn).hide();
					        $(g.nBtn).css({ 'left': nl, top: g.hDiv.offsetTop }).show();
					        var ndw = parseInt($(g.nDiv).width());
					        $(g.nDiv).css({ top: g.bDiv.offsetTop });
					        if ((nl + ndw) > $(g.gDiv).width())
					            $(g.nDiv).css('left', onl - ndw + 1);
					        else
					            $(g.nDiv).css('left', nl);
					        if ($(this).hasClass('sorted'))
					            $(g.nBtn).addClass('srtd');
					        else
					            $(g.nBtn).removeClass('srtd');
						}
					},
					function() {
					    $(this).removeClass('thOver');
					    if ($(this).attr('abbr') != p.sortname) $('div', this).removeClass('s' + p.sortorder);
					    else if ($(this).attr('abbr') == p.sortname) {
					        var no = '';
					        if (p.sortorder == 'asc') no = 'desc';
					        else no = 'asc';
					        $('div', this).addClass('s' + p.sortorder).removeClass('s' + no);
					    }
					    if (g.colCopy) {
					        $(g.cdropleft).remove();
					        $(g.cdropright).remove();
					        g.dcolt = null;
					    }
					}); //wrap content
		 	    }
			});
		},
		/**
		 * 初始化bDiv
		 */
		initbDiv : function(){
			var g = this.grid;
			var t = this.self;
			var p = this.options;
			var f = this;
			g.bDiv.className = 'bDiv';
	        $(t).before(g.bDiv);
	        $(g.bDiv)
			.css({ height: (p.height == 'auto') ? 'auto' : p.height + "px",
				   width: (p.width == 'auto') ? 'auto' : p.width + "px"
				})
			.scroll(function(e) { f.scroll(); })
			.append(t);
	        if (p.height == 'auto') {
	            $('table', g.bDiv).addClass('autoht');
	        }
		},
		/**
		 * 初始化cDrag 行拖动
		 */
		initcDrag : function(){
			var g = this.grid;
			var t = this.self;
			var p = this.options;
			var f = this;
			var cdcol = $('thead tr:first th:first', g.hDiv).get(0);
	        if (cdcol != null) {
	            g.cDrag.className = 'cDrag';
	            g.cdpad = 0;
	            g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderLeftWidth'))) ? 0 : parseInt($('div', cdcol).css('borderLeftWidth')));
	            g.cdpad += (isNaN(parseInt($('div', cdcol).css('borderRightWidth'))) ? 0 : parseInt($('div', cdcol).css('borderRightWidth')));
	            g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingLeft'))) ? 0 : parseInt($('div', cdcol).css('paddingLeft')));
	            g.cdpad += (isNaN(parseInt($('div', cdcol).css('paddingRight'))) ? 0 : parseInt($('div', cdcol).css('paddingRight')));
	            g.cdpad += (isNaN(parseInt($(cdcol).css('borderLeftWidth'))) ? 0 : parseInt($(cdcol).css('borderLeftWidth')));
	            g.cdpad += (isNaN(parseInt($(cdcol).css('borderRightWidth'))) ? 0 : parseInt($(cdcol).css('borderRightWidth')));
	            g.cdpad += (isNaN(parseInt($(cdcol).css('paddingLeft'))) ? 0 : parseInt($(cdcol).css('paddingLeft')));
	            g.cdpad += (isNaN(parseInt($(cdcol).css('paddingRight'))) ? 0 : parseInt($(cdcol).css('paddingRight')));
	            $(g.bDiv).before(g.cDrag);
	            var cdheight = $(g.bDiv).height();
	            var hdheight = $(g.hDiv).height();
	            $(g.cDrag).css({ top: -hdheight + 'px' });
	            $('thead tr:first th', g.hDiv).each(function() {
			 	    var cgDiv = document.createElement('div');
			 	    $(g.cDrag).append(cgDiv);
			 	    if (!p.cgwidth) p.cgwidth = $(cgDiv).width();
			 	    $(cgDiv).css({ height: cdheight + hdheight })
						.mousedown(function(e) { f.dragStart('colresize', e, this); })
						.mouseup(function(e){
							var number = g.colresize.n;
							if(number != "0"){
								var width = g.colresize.nw;
								var colsname = $('thead tr th', g.hDiv).eq(number).attr("abbr");
								for(var coln = 0;coln < p.colModel.length;coln++ ){
									if(p.colModel[coln].name == colsname){
										p.colModel[coln].width = width;
										break;
									}
								}
							}
						});
			 	    if ($.browser.msie && $.browser.version < 7.0) {
			 	        f.fixHeight($(g.gDiv).height());
			 	        $(cgDiv).hover(function() {
						    f.fixHeight();
						    $(this).addClass('dragging');
						},
							function() { if (!g.colresize) $(this).removeClass('dragging'); }
						);
			 	    }
				});
	            //g.rePosDrag();
	        }
		},
		/**
		 * 初始化strip斑纹
		 */
		initStrip : function (){
			var g = this.grid;
			var p = this.options;
			var f = this;
			if (p.striped)
	            $('tbody tr:odd', g.bDiv).addClass('erow');
	        if (p.resizable && p.height != 'auto') {
	            g.vDiv.className = 'vGrip';
	            $(g.vDiv)
					.mousedown(function(e) { f.dragStart('vresize', e); })
					.html('<span></span>');
	            $(g.bDiv).after(g.vDiv);
	        }
	        if (p.resizable && p.width != 'auto' && !p.nohresize) {
	            g.rDiv.className = 'hGrip';
	            $(g.rDiv)
					.mousedown(function(e) { f.dragStart('vresize', e, true); })
					.html('<span></span>')
					.css('height', $(g.gDiv).height());
	            if ($.browser.msie && $.browser.version < 7.0) {
	                $(g.rDiv).hover(function() { $(this).addClass('hgOver'); }, function() { $(this).removeClass('hgOver'); });
	            }
	            $(g.gDiv).append(g.rDiv);
	        }
		},
		/**
		 * 初始化head控制面板
		 */
		initColumnControl : function(){
			var g = this.grid;
			var p = this.options;
			var f = this;
			if ($('th', g.hDiv).length) {
				var gh = $(g.bDiv).height();
				var gtop = g.bDiv.offsetTop;
				g.nDiv.className = 'nDiv';
	            g.nDiv.innerHTML = "<table cellpadding='0' cellspacing='0'><tbody></tbody></table>";
	            $(g.nDiv).css(
				{
				    marginBottom: (gh * -1),
				    display: 'none',
				    top: gtop
				}
				).noSelect();
	            var cn = 0;
	            $('th div', g.hDiv).each(function() {
			 	    var kcol = $("th[axis='col" + cn + "']", g.hDiv)[0];
			 	    if (kcol == null) return;
			 	    var chkall = $("input[type='checkbox']", this);
			 	    if (chkall.length > 0) {
	//			 	        chkall[0].onclick = f.checkAllOrNot;
			 	    	chkall.unbind("click");
			 	    	chkall.bind("click",f,f.checkAllOrNot);
			 	        return;
			 	    }
			 	    if (kcol.toggle == false || this.innerHTML == "") {
			 	        cn++;
			 	        return;
			 	    }
			 	    var chk = 'checked="checked"';
			 	    if (kcol.style.display == 'none') chk = '';
	
			 	    $('tbody', g.nDiv).append('<tr><td class="ndcol1"><input type="checkbox" ' + chk + ' class="togCol noborder" value="' + cn + '" /></td><td class="ndcol2">' + this.innerHTML + '</td></tr>');
			 	    cn++;
				});
	            if ($.browser.msie && $.browser.version < 7.0)
	                $('tr', g.nDiv).hover(
					 	function() { $(this).addClass('ndcolover'); },
						function() { $(this).removeClass('ndcolover'); }
					);
	            $('td.ndcol2', g.nDiv).click
				(function() {
			 	    if ($('input:checked', g.nDiv).length <= p.minColToggle && $(this).prev().find('input')[0].checked) return false;
			 	    return f.toggleCol($(this).prev().find('input').val());
				});
	            $('input.togCol', g.nDiv).click
				(function() {
			 	    if ($('input:checked', g.nDiv).length < p.minColToggle && this.checked == false) return false;
			 	    $(this).parent().next().trigger('click');
			 	    //return false;
				});
	            $(g.gDiv).prepend(g.nDiv);
	            $(g.nBtn).unbind();
	            $(g.nBtn).addClass('nBtn')
				.html('<div></div>')
	            //.attr('title', 'Hide/Show Columns')
				.click(function() {
					$(g.nDiv).toggle(); return true;
				});
	            if (p.showToggleBtn)
	                $(g.gDiv).prepend(g.nBtn);
			}
		},
		/**
		 * 初始化loading画面
		 */
		initBlock : function(){
			var g = this.grid;
			var p = this.options;
			g.block.className = 'gBlock';
	        var blockloading = $("<div/>");
	        blockloading.addClass("loading");
	        $(g.block).append(blockloading);
	        var gh = $(g.bDiv).height();
	        var gtop = g.bDiv.offsetTop;
	        $(g.block).css(
			{
			    width: g.bDiv.style.width,
			    height: gh,
			    position: 'relative',
			    marginBottom: (gh * -1),
			    zIndex: 1,
			    top: gtop,
			    left: '0px'
			});
	        $(g.block).fadeTo(0, p.blockOpacity);
		},
		/**
		 * guiGrid基础html元素初始化
		 */
		initGuiGrid : function(){
			var g = this.grid;
			var p = this.options;
			g.gDiv = document.createElement('div'); //create global container
	        g.hDiv = document.createElement('div'); //create header container
	        g.bDiv = document.createElement('div'); //create body container
	        g.vDiv = document.createElement('div'); //create grip
	        g.rDiv = document.createElement('div'); //create horizontal resizer
	        g.cDrag = document.createElement('div'); //create column drag
	        g.block = document.createElement('div'); //creat blocker
	        g.nDiv = document.createElement('div'); //create column show/hide popup
	        g.nBtn = document.createElement('div'); //create column show/hide button
	        g.iDiv = document.createElement('div'); //create editable layer
	        g.tDiv = document.createElement('div'); //create toolbar
	        g.sDiv = document.createElement('div');
	        if (p.usepager) g.pDiv = document.createElement('div'); //create pager container
	        g.hTable = document.createElement('table');
		},
		/**
		 * 页面初始化
		 */
		initGuiGridHtml : function(){
			var g = this.grid;
			var p = this.options;
			var f = this;
			//set guigrid
			this.initGuiGrid();
	        //set gDiv
	        this.initgDiv();
	        //set toolbar
	        if (p.buttons) {
	            g.tDiv.className = 'tDiv';
	            g.toolbar = new GridToolBar(p.buttons,g.gDiv);
	            $(g.tDiv).append(g.toolbar.getToolBarHtml());
	            $(g.tDiv).append("<div style='clear:both'></div>");
	            $(g.gDiv).prepend(g.tDiv);
	        }
	        //set hDiv
	        this.inithDiv();
	        //set bDiv
	        this.initbDiv();
	        //add td properties
	        if (p.url == false || p.url == "") {
	            this.addCellProp();
	            //add row properties
	            this.addRowProp();
	        }
	        //set cDrag
	        this.initcDrag();
	        //add strip		
	        this.initStrip();
	        // add pager
	        if (p.usepager) {
	        	g.pagination = new Pagination(g,f,p);
	        	g.pagination.getPaginationHtml();
	        }
	        $(g.pDiv, g.sDiv).append("<div style='clear:both'></div>");
	        //setup cdrops
	        g.cdropleft = document.createElement('span');
	        g.cdropleft.className = 'cdropleft';
	        g.cdropright = document.createElement('span');
	        g.cdropright.className = 'cdropright';
	        //add block
	        this.initBlock();
	        // add column control
        	this.initColumnControl();
	        // add date edit layer
	        $(g.iDiv)
			.addClass('iDiv')
			.css({ display: 'none' });
	        $(g.bDiv).append(g.iDiv);
	        // add grid events
	        $(g.bDiv)
			.hover(function() { $(g.nDiv).hide(); $(g.nBtn).hide(); }, function() { if (g.multisel) g.multisel = false; });
	        $(g.gDiv)
			.hover(function() { }, function() { $(g.nDiv).hide(); $(g.nBtn).hide(); });
	        //add document events
	        $(document)
			.mousemove(function(e) { f.dragMove(e); })
			.mouseup(function(e) { f.dragEnd(); })
			.hover(function() { }, function() { f.dragEnd(); });
	        //browser adjustments
	        if ($.browser.msie && $.browser.version < 7.0) {
	            $('.hDiv,.bDiv,.mDiv,.pDiv,.vGrip,.tDiv, .sDiv', g.gDiv)
				.css({ width: '100%' });
	            $(g.gDiv).addClass('ie6');
	            if (p.width != 'auto') $(g.gDiv).addClass('ie6fullwidthbug');
	        }
		},
		/**
		 * 
		 */
		load : function(){
			var p = this.options;
			var f = this;
			//标题
			//init divs
			this.initGuiGridHtml();
//	        g.prototype.rePosDrag(this);
	        this.rePosDrag();
	        this.fixHeight();
	        // load data
	        if (p.url && p.autoload) {
	            f.populate();
	        }
		},
		/**
		 * 
		 */
		reload : function(){
			var p = this.options;
			var g = this.grid;
			this.destroy(g);
			$("TABLE",g.hDiv).html(g.head.reload(p.colModel,p.showcheckbox));//重构hdiv thead
			this.bindHeadEvent();//绑定thead方法
			this.initColumnControl();//重构head控制面板
			this.rePosDrag();
	        this.fixHeight();
			this.populate();
		},
		
		/**
		 * 
		 */
		destroy : function(g){
			$('thead tr:first th', g.hDiv).each(function() {
				$(this).unbind();
			});//
			$('th div', g.hDiv).each(function() {
		 	    var chkall = $("input[type='checkbox']", this);
		 	    if (chkall.length > 0) {
		 	    	chkall.unbind("click");
		 	        return;
		 	    }
			});
            if ($.browser.msie && $.browser.version < 7.0)
                $('tr', g.nDiv).unbind();
            $('td.ndcol2', g.nDiv).unbind();
            $('input.togCol', g.nDiv).unbind();
            $(g.nBtn).unbind();
		},
		
		/**
		 * 
		 */
		hset: {},
		/**
		 * 行拖动定位
		 */
        rePosDrag: function() {
        	var g = this.grid;
			var p = this.options;
            var cdleft = 0 - g.hDiv.scrollLeft;
            if (g.hDiv.scrollLeft > 0) cdleft -= Math.floor(p.cgwidth / 2);
            $(g.cDrag).css({ top: g.hDiv.offsetTop + 1 });
            var cdpad = g.cdpad;
            $('div', g.cDrag).hide();
            //update by xuanye ,避免jQuery :visible 无效的bug
            var i = 0;
            $('thead tr:first th:visible', g.hDiv).each(function() {
                if ($(this).css("display") == "none") {
                    return;
                }
                var n = i;
                //var n = $('thead tr:first th:visible', g.hDiv).index(this);			 	  
                var cdpos = parseInt($('div', this).width());
                var ppos = cdpos;
                if (cdleft == 0)
                    cdleft -= Math.floor(p.cgwidth / 2);
                cdpos = cdpos + cdleft + cdpad;
                $('div:eq(' + n + ')', g.cDrag).css({ 'left': cdpos + 'px' }).show();
                cdleft = cdpos;
                i++;
           });
        },
        /**
         * 高度计算
         * @param newH
         */
        fixHeight: function(newH) {
        	var g = this.grid;
			var p = this.options;
            newH = false;
            if (!newH) newH = $(g.bDiv).height();
            var hdHeight = $(g.hDiv).height();
            $('div', g.cDrag).each(function() {
				$(this).height(newH + hdHeight);
			});
            var nd = parseInt($(g.nDiv).height());
            if (nd > newH)
                $(g.nDiv).height(newH).width(200);
            else
                $(g.nDiv).height('auto').width('auto');
            $(g.block).css({ height: newH, marginBottom: (newH * -1) });
            var hrH = g.bDiv.offsetTop + newH;
            if (p.height != 'auto' && p.resizable) hrH = g.vDiv.offsetTop;
            $(g.rDiv).css({ height: hrH });
        },
        /**
         * 拖动事件开始
         * @param dragtype 拖动类型[colresize,vresize,colMove]
         * @param e 定位
         * @param obj 拖动对象
         */
        dragStart: function(dragtype, e, obj) { //default drag function start
        	var g = this.grid;
			var p = this.options;
            if (dragtype == 'colresize') //column resize
            {
                $(g.nDiv).hide(); $(g.nBtn).hide();
                var n = $('div', g.cDrag).index(obj);
                //var ow = $('th:visible div:eq(' + n + ')', this.hDiv).width();
                var ow = $('th:visible:eq(' + n + ') div', g.hDiv).width();
                $(obj).addClass('dragging').siblings().hide();
                $(obj).prev().addClass('dragging').show();

                g.colresize = { startX: e.pageX, ol: parseInt(obj.style.left), ow: ow, n: n };
                $('body').css('cursor', 'col-resize');
            }
            else if (dragtype == 'vresize') //table resize
            {
                var hgo = false;
                $('body').css('cursor', 'row-resize');
                if (obj) {
                    hgo = true;
                    $('body').css('cursor', 'col-resize');
                }
                g.vresize = { h: p.height, sy: e.pageY, w: p.width, sx: e.pageX, hgo: hgo };
            }

            else if (dragtype == 'colMove') //column header drag
            {
                $(g.nDiv).hide(); $(g.nBtn).hide();
                g.hset = $(g.hDiv).offset();
                g.hset.right = g.hset.left + $('table', g.hDiv).width();
                g.hset.bottom = g.hset.top + $('table', g.hDiv).height();
                g.dcol = obj;
                g.dcoln = $('th', g.hDiv).index(obj);
                g.colCopy = document.createElement("div");
                g.colCopy.className = "colCopy";
                g.colCopy.innerHTML = obj.innerHTML;
                if ($.browser.msie) {
                    g.colCopy.className = "colCopy ie";
                }
                $(g.colCopy).css({ 'position': 'absolute', 'float': 'left', 'display': 'none', 'textAlign': obj.align });
                $('body').append(g.colCopy);
                $(g.cDrag).hide();
            }
            $('body').noSelect();
        },
        /**
         * grid size
         */
        reSize: function() {
			var p = this.options;
            this.grid.gDiv.style.width = p.width;
            this.grid.bDiv.style.height = p.height;
        },
        /**
         * 拖动中
         * @param e 定位
         */
        dragMove: function(e) {
        	var g = this.grid;
			var p = this.options;
            if (g.colresize) //column resize
            {
                var n = g.colresize.n;
                var diff = e.pageX - g.colresize.startX;
                var nleft = g.colresize.ol + diff;
                var nw = g.colresize.ow + diff;
                if (nw > p.minwidth) {
                    $('div:eq(' + n + ')', g.cDrag).css('left', nleft);
                    g.colresize.nw = nw;
                }
            }
            else if (g.vresize) //table resize
            {
                var v = g.vresize;
                var y = e.pageY;
                var diff = y - v.sy;
                if (!p.defwidth) p.defwidth = p.width;
                if (p.width != 'auto' && !p.nohresize && v.hgo) {
                    var x = e.pageX;
                    var xdiff = x - v.sx;
                    var newW = v.w + xdiff;
                    if (newW > p.defwidth) {
                        g.gDiv.style.width = newW + 'px';
                        p.width = newW;
                    }
                }
                var newH = v.h + diff;
                if ((newH > p.minheight || p.height < p.minheight) && !v.hgo) {
                    g.bDiv.style.height = newH + 'px';
                    p.height = newH;
                    this.fixHeight(newH);
                }
                v = null;
            }
            else if (g.colCopy) {
                $(g.dcol).addClass('thMove').removeClass('thOver');
                if (e.pageX > g.hset.right || e.pageX < g.hset.left || e.pageY > g.hset.bottom || e.pageY < g.hset.top) {
                    //this.dragEnd();
                    $('body').css('cursor', 'move');
                }
                else
                    $('body').css('cursor', 'pointer');
                $(g.colCopy).css({ top: e.pageY + 10, left: e.pageX + 20, display: 'block' });
            }
        },
        /**
         * 拖动结束
         */
        dragEnd: function() {
        	var g = this.grid;
            if (g.colresize) {
                var n = g.colresize.n;
                var nw = g.colresize.nw;
                $('th:visible:eq(' + n + ') div', g.hDiv).css('width', nw);
                $('tr', g.bDiv).each(function() {
					$('td:visible:eq(' + n + ') div', this).css('width', nw);
				});
                g.hDiv.scrollLeft = g.bDiv.scrollLeft;
                $('div:eq(' + n + ')', g.cDrag).siblings().show();
                $('.dragging', g.cDrag).removeClass('dragging');
                this.rePosDrag();
                this.fixHeight();
                g.colresize = false;
            }
            else if (g.vresize) {
                g.vresize = false;
            }
            else if (g.colCopy) {
                $(g.colCopy).remove();
                if (g.dcolt != null) {
                    if (g.dcoln > g.dcolt)
                    { $('th:eq(' + g.dcolt + ')', g.hDiv).before(g.dcol); }
                    else
                    { $('th:eq(' + g.dcolt + ')', g.hDiv).after(g.dcol); }
                    this.switchCol(g.dcoln, g.dcolt);
                    $(g.cdropleft).remove();
                    $(g.cdropright).remove();
                    this.rePosDrag();
                }
                g.dcol = null;
                g.hset = null;
                g.dcoln = null;
                g.dcolt = null;
                g.colCopy = null;
                $('.thMove', g.hDiv).removeClass('thMove');
                $(g.cDrag).show();
            }
            $('body').css('cursor', 'default');
            $('body').noSelect(false);
        },
        /**
         * col展示
         * @param cid col序号
         * @param visible 
         * @returns
         */
        toggleCol: function(cid, visible) {
        	var g = this.grid;
			var t = this.self;
			var p = this.options;
            var ncol = $("th[axis='col" + cid + "']", this.hDiv)[0];
            var n = $('thead th', g.hDiv).index(ncol);
            var cb = $('input[value=' + cid + ']', g.nDiv)[0];
            if (visible == null) {
                visible = ncol.hide;
            }
            if ($('input:checked', g.nDiv).length < p.minColToggle && !visible) return false;
            if (visible) {
                ncol.hide = false;
                $(ncol).show();
                cb.checked = true;
            }
            else {
                ncol.hide = true;
                $(ncol).hide();
                cb.checked = false;
            }
            $('tbody tr', t).each(function() {
				if (visible)
					$('td:eq(' + n + ')', this).show();
				else
					$('td:eq(' + n + ')', this).hide();
			});
            this.rePosDrag();
            if (p.onToggleCol) p.onToggleCol(cid, visible);
            return visible;
        },
        /**
         * col转换
         * @param cdrag 
         * @param cdrop 
         */
        switchCol: function(cdrag, cdrop) { //switch columns
        	var g = this.grid;
			var t = this.self;
            $('tbody tr', t).each(function() {
				if (cdrag > cdrop)
					$('td:eq(' + cdrop + ')', this).before($('td:eq(' + cdrag + ')', this));
				else
					$('td:eq(' + cdrop + ')', this).after($('td:eq(' + cdrag + ')', this));
			});
            //switch order in nDiv
            if (cdrag > cdrop)
                $('tr:eq(' + cdrop + ')', g.nDiv).before($('tr:eq(' + cdrag + ')', g.nDiv));
            else
                $('tr:eq(' + cdrop + ')', g.nDiv).after($('tr:eq(' + cdrag + ')', g.nDiv));
            if ($.browser.msie && $.browser.version < 7.0) $('tr:eq(' + cdrop + ') input', g.nDiv)[0].checked = true;
            g.hDiv.scrollLeft = g.bDiv.scrollLeft;
        },
        /**
         * 滚动条同步
         */
        scroll: function() {
            this.grid.hDiv.scrollLeft = this.grid.bDiv.scrollLeft;
            this.rePosDrag();
        },
        /**
         * 隐藏loading图层
         */
        hideLoading: function() {
        	var g = this.grid;
			var p = this.options;
            $('.pReload', g.pDiv).removeClass('loading');
            if (p.hideOnSubmit) $(g.block).remove();
            $('.pPageStat', g.pDiv).html(p.errormsg);
            g.loading = false;
        },
        /**
         * 增加数据区数据
         * @param data
         * @returns {Boolean}
         */
        addData : function(data) {
        	var g = this.grid;
			var p = this.options;
			var t = this.self;
            // log.trace("将数据转换成table开始");
            if (p.preProcess)
            { data = p.preProcess(data); }
            $('.pReload', g.pDiv).removeClass('loading');
            g.loading = false;
            if (!data) {
                $('.pPageStat', g.pDiv).html(p.errormsg);
                return false;
            }
            var temp = p.total;
            p.total = data.total;
            if (p.total < 0) {
                p.total = temp;
            }
            if (p.total == 0) {
                $('tr, a, td, div', t).unbind();
                $(t).empty();
                p.pages = 1;
                p.page = 1;
                this.buildpager();
                $('.pPageStat', g.pDiv).html(p.nomsg);
                if (p.hideOnSubmit) $(g.block).remove();
                return false;
            }
            p.pages = Math.ceil(p.total / p.rp);
            p.page = data.page;
            this.buildpager();
            var options = {};
            options.dataType = "json";
            options.nowrap = p.nowrap;
            options.sortname = p.sortname;
            options.striped = p.striped;
            options.keyCol = p.keyCol;
            if(g.body){
            	g.body.option({data:data,options:options,headclass:g.head});
            }else{
            	g.body = new GridBody(data,options,g.head);
            }
            var tbhtml = g.body.getBodyHtml(g.hDiv);
            $(t).html(tbhtml);
            //this.rePosDrag();
            this.addRowProp();
            if (p.onSuccess) p.onSuccess();
            if (p.hideOnSubmit) $(g.block).remove(); //$(t).show();
            g.hDiv.scrollLeft = g.bDiv.scrollLeft;
            if ($.browser.opera) $(t).css('visibility', 'visible');
            // log.diff("将数据转换成table结束");
        },
        /**
         * 排序
         * @param th
         * @returns {Boolean}
         */
        changeSort: function(th) { //change sortorder
        	var g = this.grid;
			var p = this.options;
            if (g.loading) return true;
            $(g.nDiv).hide(); $(g.nBtn).hide();
            if (p.sortname == $(th).attr('abbr')) {
                if (p.sortorder == 'asc') p.sortorder = 'desc';
                else p.sortorder = 'asc';
            }
            $(th).addClass('sorted').siblings().removeClass('sorted');
            $('.sdesc', this.hDiv).removeClass('sdesc');
            $('.sasc', this.hDiv).removeClass('sasc');
            $('div', th).addClass('s' + p.sortorder);
            p.sortname = $(th).attr('abbr');
            if (p.onChangeSort)
                p.onChangeSort(p.sortname, p.sortorder);
            else
                this.populate();
        },
        /**
         * 
         */
        buildpager: function() { //rebuild pager based on new properties
        	var g = this.grid;
			var p = this.options;
            $('.pcontrol input', g.pDiv).val(p.page);
            $('.pcontrol span', g.pDiv).html(p.pages);
            var r1 = (p.page - 1) * p.rp + 1;
            var r2 = r1 + p.rp - 1;
            if (p.total < r2) r2 = p.total;
            var stat = p.pagestat;
            stat = stat.replace(/{from}/, r1);
            stat = stat.replace(/{to}/, r2);
            stat = stat.replace(/{total}/, p.total);
            $('.pPageStat', g.pDiv).html(stat);
        },
        /**
         * 数据区设置
         * @param np
         * @returns {Boolean}
         */
        populate: function(np) { //get latest data 
        	var g = this.grid;
			var t = this.self;
			var p = this.options;
        	var f = this;
            //log.trace("开始访问数据源");
            if (g.loading) return true;
            if (p.onSubmit) {
                var gh = p.onSubmit();
                if (!gh) return false;
            }
            g.loading = true;
            if(np) p = $.extend(p, np); 
            if (!p.url) return false;
            $('.pPageStat', g.pDiv).html(p.procmsg);
            $('.pReload', g.pDiv).addClass('loading');
            $(g.block).css({ top: g.bDiv.offsetTop });
            if (p.hideOnSubmit) $(g.gDiv).prepend(g.block); //$(t).hide();
            if ($.browser.opera) $(t).css('visibility', 'hidden');
            if (!p.newp) p.newp = 1;
            if (p.page > p.pages) p.page = p.pages;
            //var param = {page:p.newp, rp: p.rp, sortname: p.sortname, sortorder: p.sortorder, query: p.query, qtype: p.qtype};
            var param = [
				 { name: 'page', value: p.newp }
				, { name: 'rp', value: p.rp }
				, { name: 'sortname', value: p.sortname }
				, { name: 'sortorder', value: p.sortorder }
				,{ name: 'pages', value: p.pages }
			];
			
			if (p.extParam) {
                for (var pi = 0; pi < p.extParam.length; pi++) param[param.length] = p.extParam[pi];
            }
			
            $.ajax({
                type: p.method,
                url: p.url,
                data: param,
                dataType: 'json',
                success : function(data) {
				    if((typeof data).toLocaleUpperCase() == 'STRING' ){
				          var temp = eval('('+data+')');
				          data = temp;
				     }
					if (data != null && data.error != null) {
						if (p.onError) {
							
							p.onError(data);
							f.hideLoading();
						}
						
					} else {
						f.addData(data);
					}
					//为数据区添加点击事件，用来处理button的使用规则
				/*	$(g.bDiv).click(function(e){
						$("div.fbutton").each(function(g){
							if($(this).attr("disabled") &&($(this).attr("disabled")==true || $(this).attr("disabled")=="true" ||$(this).attr("disabled") == "disabled")  ){
								if($(this).attr("rule")=='1'){
									alert("rule:1");
								}else if($(this).attr("rule")=='2'){
									
								}
							}
						});
						
					});*/
				},
				error: function(data) { try { if (p.onError) { p.onError(data); } else { alert("获取数据发生异常;"); } f.hideLoading(); } catch (e) { } }
            });
        },
        /**
         * page切换
         * @param ctype
         * @returns {Boolean}
         */
        changePage: function(ctype) { //change page
        	var g = this.grid;
			var p = this.options;
            if (g.loading) return true;
            switch (ctype) {
                case 'first': p.newp = 1; break;
                case 'prev': if (p.page > 1) p.newp = parseInt(p.page) - 1; break;
                case 'next': if (p.page < p.pages) p.newp = parseInt(p.page) + 1; break;
                case 'last': p.newp = p.pages; break;
                case 'input':
                    var nv = parseInt($('.pcontrol input', g.pDiv).val());
                    if (isNaN(nv)) nv = 1;
                    if (nv < 1) nv = 1;
                    else if (nv > p.pages) nv = p.pages;
                    $('.pcontrol input', g.pDiv).val(nv);
                    p.newp = nv;
                    break;
            }
            if (p.newp == p.page) return false;
            if (p.onChangePage)
                p.onChangePage(p.newp);
            else
                this.populate();
        },
        /**
         * cell属性
         * @param n
         * @param ptr
         * @param pth
         * @param t
         */
        cellProp: function(n, ptr, pth,t) {
			var p = this.options;
            var tdDiv = document.createElement('div');
            if (pth != null) {
                if (p.sortname == $(pth).attr('abbr') && p.sortname) {
                    this.className = 'sorted';
                }
                $(tdDiv).css({ textAlign: pth.align, width: $('div:first', pth)[0].style.width });
                if (pth.hide) $(this).css('display', 'none');
            }
            if (p.nowrap == false) $(tdDiv).css('white-space', 'normal');
            if (this.innerHTML == '') this.innerHTML = '&nbsp;';
            tdDiv.innerHTML = this.innerHTML;
            var prnt = $(this).parent()[0];
            var pid = false;
            if (prnt.id) pid = prnt.id.substr(3);
            if (pth != null) {
                if (pth.process)
                { pth.process(tdDiv, pid); }
            }
            $("input.itemchk", tdDiv).each(function() {
                $(this).click(function() {
                    if (this.checked) {
                        $(ptr).addClass("trSelected");
                    }
                    else {
                        $(ptr).removeClass("trSelected");
                    }
                    if (p.onrowchecked) {
                        p.onrowchecked.call(this);
                    }
                });
            });
            $(this).empty().append(tdDiv).removeAttr('width'); //wrap content
            //add editable event here 'dblclick',如果需要可编辑在这里添加可编辑代码 
        },
        /**
         * 增加cell属性 
         */
        addCellProp: function() {
        	var g = this.grid;
        	var t = this;
            var $gF = this.cellProp;
            $('tbody tr td', g.bDiv).each(function() {
			    var n = $('td', $(this).parent()).index(this);
			    var pth = $('th:eq(' + n + ')', g.hDiv).get(0);
			    var ptr = $(this).parent();
			    $gF.call(this, n, ptr, pth,t);
			});
            $gF = null;
        },
        /**
         * 获得所有序中行信息
         * @returns {Array}
         */
        getCheckedRows: function() {
        	var g = this.grid;
            var ids = [];
            $(":checkbox:checked", g.bDiv).each(function() {
                ids.push($(this).val());
            });
            return ids;
        },
        /**
         * 
         * @param obj
         * @returns {___anonymous50580_50659}
         */
        getCellDim: function(obj) // get cell prop for editable event
        {
            var ht = parseInt($(obj).height());
            var pht = parseInt($(obj).parent().height());
            var wt = parseInt(obj.style.width);
            var pwt = parseInt($(obj).parent().width());
            var top = obj.offsetParent.offsetTop;
            var left = obj.offsetParent.offsetLeft;
            var pdl = parseInt($(obj).css('paddingLeft'));
            var pdt = parseInt($(obj).css('paddingTop'));
            return { ht: ht, wt: wt, top: top, left: left, pdl: pdl, pdt: pdt, pht: pht, pwt: pwt };
        },
        /**
         * row属性
         * @param t
         */
        rowProp: function(t) {
        	var p = t.options;
        	var g = t.grid;
            if (p.rowhandler) {
                p.rowhandler(this);
            }
            if ($.browser.msie && $.browser.version < 7.0) {
                $(this).hover(function() { $(this).addClass('trOver'); }, function() { $(this).removeClass('trOver'); });
            }
        },
        /**
         * 增加row属性
         */
        addRowProp: function() {
        	var g = this.grid;
			var p = this.options;
        	var f = this;
            var $gF = this.rowProp;
            $('tbody tr', g.bDiv).each(
                function() {
                    $("input.itemchk", this).each(function() {
                        var ptr = $(this).parent().parent().parent();
                        var pck = this;
                        $(ptr).click(function() {
                            if (pck.checked) {
                            	if(ptr.hasClass("trSelected")){
                            		ptr.removeClass("trSelected");
                            		$(pck).attr("checked",false);
                            	}else{
                            		ptr.addClass("trSelected");
                            		if(!pck.checked){
                                    	$(pck).attr("checked",true);
                                    }
                            	}
                            }else {
                            	if(!ptr.hasClass("trSelected")){
                            		$(pck).attr("checked",true);
                            		ptr.addClass("trSelected");
                            	}else{
                            		ptr.removeClass("trSelected");
                            	}
                            }
                            if (p.onrowchecked) {
                                p.onrowchecked.call(this);
                            }
                            //alert(this.getCheckedRows());
                            $("div.fbutton").each(function(){
                            	var ids = [];
                                $(":checkbox:checked", g.bDiv).each(function() {
                                    ids.push($(this).val());
                                });
								if($(this).attr("rule")=='1'){
									if(ids.length==1){
										$(this).attr("disabled","");
									}else{
										$(this).attr("disabled","disabled");
									}
								}else if($(this).attr("rule")=='2'){
									if(ids.length > 0){
										$(this).attr("disabled","");
									}else{
										$(this).attr("disabled","disabled");
									}
								}
    						});
                        });
                    });
                    $gF.call(this,f);
                }
            );
            $gF = null;
        },
        /**
         * 全选按钮
         * @param t
         * @param parent
         */
        checkAllOrNot: function(t,parent) {
        	var p = t.data.options;
        	var g = t.data.grid;
            var ischeck = $(this).attr("checked");
            $('tbody tr', g.bDiv).each(function() {
                if (ischeck) {
                    $(this).addClass("trSelected");
                }
                else {
                    $(this).removeClass("trSelected");
                }
            });
            $("input.itemchk", g.bDiv).each(function() {
                this.checked = ischeck;
                //Raise Event
                if (p.onrowchecked) {
                    p.onrowchecked.call(this);
                }
            });
        },
        /**
         * 显示页
         */
        pager: 0
        
	};
	/*********************
	*
	*	工具栏 
	* 
	*/
	var GridToolBar = Class.create();
	/**
	 * param data 名称 : 工具栏按钮数据
	 * 		      格式 ：{
	 * 					 	name : 'Delete',   			  //按钮name
	 *				     	displayname : "删除",  		  //按钮value
	 *				 	 	bclass : 'Delete',    		  //按钮class
	 *				 	 	onpress : toolbarItem_onclick //按钮onlick  返回参数为 name guigridobj
	 *				 	 }
	 * param guigridobj 名称： onclick事件后需返回的对象
	 */
	GridToolBar.prototype = {
		/**
		 * 初始化
		 * @param data
		 * @param guigridobj
		 */
		initialize :function (data,guigridobj){
			this.data = data;
			this.guigridobj = guigridobj;
		},
		/**
		 * 获得工具栏HTML
		 * @returns {___tDiv231}
		 */
		getToolBarHtml : function(){
			var data = this.data;
			var guigridobj = this.guigridobj;
			var tDiv2 = document.createElement('div');
            tDiv2.className = 'tDiv2';
            for (i = 0; i < data.length; i++) {
                var btn = data[i];
                if (!btn.separator) {
                    var btnDiv = document.createElement('div');
                    btnDiv.className = 'fbutton';
                    var rule = "rule='"+btn.rule+"' ";
                    btnDiv.innerHTML = "<div><span>" + btn.displayname + "</span></div>";
                    if (btn.title) {
                        btnDiv.title = btn.title;
                    }
                    if (btn.bclass)
                        $('span', btnDiv)
							.addClass(btn.bclass);
                    btnDiv.onpress = btn.onpress;
                    btnDiv.name = btn.name;
                    btnDiv.id=btn.name;
                    btnDiv.rule=btn.rule;
                    btnDiv.disabled=btn.rule=='0'?"":"disabled";
                    if (btn.onpress) {
                        $(btnDiv).click(function() {
							this.onpress(this.name, guigridobj);
						});
                    }
                    $(tDiv2).append(btnDiv);
                    if ($.browser.msie && $.browser.version < 7.0) {
                        $(btnDiv).hover(function() { $(this).addClass('fbOver'); }, function() { $(this).removeClass('fbOver'); });
                    }
                } else {
                    $(tDiv2).append("<div class='btnseparator'></div>");
                }
            }
            return tDiv2;
		}
	};
	
	/*********************
	*
	*	分页 
	* 
	*/
	var Pagination = Class.create();
	Pagination.prototype = {
		/**
		 * 初始化
		 * @param g
		 * @param guigridobj
		 * @param options
		 */
		initialize : function(grid,guigridobj,options){
			this.grid = grid;
			this.guigridobj = guigridobj;
			this.options = options;
		},
		/**
		 * 获得基础分页HTML
		 */
		getDefaultHtml : function(){
			var g = this.grid;
			var f = this.guigridobj;
			var p = this.options;
			g.pDiv.className = 'pDiv';
            g.pDiv.innerHTML = '<div class="pDiv2"></div>';
            $(g.bDiv).after(g.pDiv);
            var html = '<div class="pGroup"><div class="pFirst pButton" title="转到第一页"><span></span></div><div class="pPrev pButton" title="转到上一页"><span></span></div> </div><div class="btnseparator"></div> <div class="pGroup"><span class="pcontrol">当前 <input type="text" size="1" value="1" /> ,总页数 <span> 1 </span></span></div><div class="btnseparator"></div><div class="pGroup"> <div class="pNext pButton" title="转到下一页"><span></span></div><div class="pLast pButton" title="转到最后一页"><span></span></div></div><div class="btnseparator"></div><div class="pGroup"> <div class="pReload pButton" title="刷新"><span></span></div> </div> <div class="btnseparator"></div><div class="pGroup"><span class="pPageStat"></span></div>';
            $('div', g.pDiv).html(html);
            $('.pReload', g.pDiv).click(function() { f.populate(); });
            $('.pFirst', g.pDiv).click(function() { f.changePage('first'); });
            $('.pPrev', g.pDiv).click(function() { f.changePage('prev'); });
            $('.pNext', g.pDiv).click(function() { f.changePage('next'); });
            $('.pLast', g.pDiv).click(function() { f.changePage('last'); });
            $('.pcontrol input', g.pDiv).keydown(function(e) { 
            	if (e.keyCode == 13){ 
            		f.changePage('input');
            	}
            });
            if ($.browser.msie && $.browser.version < 7) $('.pButton', g.pDiv).hover(function() { $(this).addClass('pBtnOver'); }, function() { $(this).removeClass('pBtnOver'); });
            if (p.useRp) {
                var opt = "";
                for (var nx = 0; nx < p.rpOptions.length; nx++) {
                    if (p.rp == p.rpOptions[nx]) sel = 'selected="selected"'; else sel = '';
                    opt += "<option value='" + p.rpOptions[nx] + "' " + sel + " >" + p.rpOptions[nx] + "&nbsp;&nbsp;</option>";
                };
                $('.pDiv2', g.pDiv).prepend("<div class='pGroup'>每页 <select name='rp'>" + opt + "</select>条</div> <div class='btnseparator'></div>");
                $('select', g.pDiv).change(
					function() {
					    if (p.onRpChange)
					        p.onRpChange(+this.value);
					    else {
					        p.newp = 1;
					        p.rp = +this.value;
					        f.populate();
					    }
					}
				);
            }
		},
		/**
		 * 获得分页HTML
		 */
		getPaginationHtml : function(){
			var p = this.options;
			this.getDefaultHtml();
		}
	};
	
	/*********************
	*
	*	绑定到jQuery widget
	* 
	*/
	$.widget("ui.guigrid", {
		/**
		 * 初始化
		 * @returns
		 */
		_init: function() {
			if (this.grid){
	        	return $(this).reload(this.grid.options); //如果Grid已经存在则刷新
	        }else{
				var grid = new GuiGrid(this);
				grid.load();
				this.grid = grid;
	        }
		},
		/**
		 * reload
		 * @param p
		 */
		reload : function(options){
			if (this.grid && this.grid.options.url) this.grid.populate(options);
		},
		
		option : function( options ){
			if(this.grid){
				this.grid.options = $.extend(true,this.grid.options,options);
				this.grid.reload();
			}
			return true;
		},
		
	    /**
	     * 获得checkbox选中行内容
	     * @returns
	     */
	    getCheckedRows: function() {
	        if (this.grid) {
	            return this.grid.getCheckedRows();
	        }
	        return [];
	    },
	    /**
	     * 设置数据区数据
	     * @param data
	     */
	    addData: function(data) { // function to add data to grid
            if (this.grid) 
            	this.grid.addData(data);
	    },
	    
	    widget: function() {
			return this.grid;
		}
	});
	
	$.fn.noSelect = function(p){
        if (p == null)
            prevent = true;
        else
            prevent = p;
        if (prevent) {
            return this.each(function() {
                if ($.browser.msie || $.browser.safari) $(this).bind('selectstart', function() { return false; });
                else if ($.browser.mozilla) {
                    $(this).css('MozUserSelect', 'none');
                    $('body').trigger('focus');
                }
                else if ($.browser.opera) $(this).bind('mousedown', function() { return false; });
                else $(this).attr('unselectable', 'on');
            });
        } else {
            return this.each(function() {
                if ($.browser.msie || $.browser.safari) $(this).unbind('selectstart');
                else if ($.browser.mozilla) $(this).css('MozUserSelect', 'inherit');
                else if ($.browser.opera) $(this).unbind('mousedown');
                else $(this).removeAttr('unselectable', 'on');
            });
        }
    };
	$.ui.guigrid.prototype.options = {
		height: 200, //grid插件的高度，单位为px
        width: 'auto', //宽度值，auto表示根据每列的宽度自动计算
        striped: true, //是否显示斑纹效果，默认是奇偶交互的形式
        novstripe: false,//表格线
        minwidth: 30, //列的最小宽度
        minheight: 80, //列的最小高度
        resizable: false, //resizable table是否可伸缩
        url: false, //ajax url,ajax方式对应的url地址
        method: 'POST', // data sending method,数据发送方式
        dataType: 'json', // type of data loaded,数据加载的类型，xml,json
        errormsg: '发生错误', //错误提升信息
        usepager: false, //是否分页
        nowrap: true, //是否不换行
        page: 1, //current page,默认当前页
        total: 1, //total pages,总页面数
        useRp: true, //use the results per page select box,是否可以动态设置每页显示的结果数
        rp: 25, // results per page,每页默认的结果数
        rpOptions: [10, 15, 20, 25, 40, 100], //可选择设定的每页结果数
        pagestat: '显示记录从{from}到{to}，总数 {total} 条', //显示当前页和总页面的样式
        procmsg: '正在处理数据，请稍候 ...', //正在处理的提示信息
        nomsg: '没有符合条件的记录存在', //无结果的提示信息
        minColToggle: 1, //minimum allowed column to be hidden
        showToggleBtn: true, //show or hide column toggle popup
        hideOnSubmit: true, //显示遮盖
        showTableToggleBtn: false, //显示隐藏Grid 
        autoload: true, //自动加载
        blockOpacity: 0.5, //透明度设置
        onToggleCol: false, //当在行之间转换时
        onChangeSort: false, //当改变排序时
        onSuccess: false, //成功后执行
        onSubmit: false, // using a custom populate function,调用自定义的计算函数
        showcheckbox: false, //是否显示checkbox       
        rowhandler: false, //是否启用行的扩展事情功能
        extParam: {},
        //Style
        gridClass: "bbit-grid",
        onrowchecked: false
	};
})(jQuery);